"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments)).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
    return { next: verb(0), "throw": verb(1), "return": verb(2) };
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var common = require("../../../common");
var User = require("../../../models/user");
var Friend = require("../../../models/friend");
var Game = require("../../../models/game");
var PaymentRecord = require("../../../models/paymentRecord");
var GiftRecord = require("../../../models/giftRecord");
// import Group = require('../../../models/group');
var Match = require("../../../models/match");
var sequence = require("../../../models/sequence");
var CreditGoods = require("../../../models/creditExchangeGoodRecord");
module.exports = function (app) {
    return new Remote(app);
};
var Remote = function (app) {
    this.app = app;
    this.channelService = app.get('channelService');
};
var remote = Remote.prototype;
remote.updateSkin = function (uid, skinId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.skins.indexOf(skinId) == -1) {
                        console.warn("user.skins.indexOf(skinId) == -1");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.skin = skinId;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.buySkin = function (uid, skinId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, game, skin;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb(0);
                        return [2 /*return*/];
                    }
                    skin = game.skins.find(function (s) { return s.id == skinId; });
                    if (!skin) {
                        console.warn("!skin");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.currencys.gold < skin.price) {
                        console.warn("user.currencys.gold < skin.price");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.currencys.gold -= skin.price;
                    user.skin = skin.id;
                    user.skins.push(skin.id);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.updateTheme = function (uid, themeId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.themes.indexOf(themeId) == -1) {
                        console.warn("user.themes.indexOf(skinId) == -1");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.theme = themeId;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.buyTheme = function (uid, themeId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, game, theme;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb(0);
                        return [2 /*return*/];
                    }
                    theme = game.themes.find(function (s) { return s.id == themeId; });
                    if (!theme) {
                        console.warn("!theme");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.currencys.gold < theme.price) {
                        console.warn("user.currencys.gold < theme.price");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.currencys.gold -= theme.price;
                    user.theme = theme.id;
                    user.themes.push(theme.id);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
// remote.bingPromoteCode = async function(uid, code, cb) {
// 	let user = await User.Model.findById(uid).exec();
// 	if (!user) { console.warn("!user"); cb(0); return; }
// 	if (user.promote.isPromoter)
// 		{ console.warn("user.promote.isPromoter"); cb(2); return; } // 自己是推廣人無法綁定
// 	if (user.promote.bingUser)
// 		{ console.warn("user.promote.bingUser"); cb(3); return; } // 已綁定
// 	let bingUser = await User.Model.findOne({
// 		"promote.isPromoter": true,
// 		"promote.code": code,
// 	}).exec();
// 	if (!bingUser)
// 		{ console.warn("!bingUser"); cb(4); return; } // 推廣人不存在
// 	if (bingUser._id.equals(user._id))
// 		{ console.warn("bingUser._id.equals(user._id)"); cb(5); return; } // 不能綁定自己,正常不會發生
// 	user.promote.bingUser = bingUser._id;
// 	user = await user.save();
// 	cb(1);
// };
remote.addFriend = function (uid, friendUid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, target, friend, i;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (uid.toString() == friendUid.toString()) {
                        console.warn("uid.toString() == friendUid.toString()");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(friendUid).exec()];
                case 2:
                    target = _a.sent();
                    if (!target) {
                        console.warn("!target");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.find(user._id, target._id)];
                case 3:
                    friend = _a.sent();
                    if (friend) {
                        console.warn("friend");
                        cb(0);
                        return [2 /*return*/];
                    } // 已經是朋友
                    friend = new Friend.Model();
                    friend.users = [];
                    friend.users.push({ user: user._id, readAt: 0 });
                    friend.users.push({ user: target._id, readAt: 0 });
                    friend.addBy = user._id;
                    friend.isVerified = false;
                    return [4 /*yield*/, friend.save()];
                case 4:
                    friend = _a.sent();
                    i = 0;
                    _a.label = 5;
                case 5:
                    if (!(i < friend.users.length))
                        return [3 /*break*/, 8];
                    return [4 /*yield*/, Friend.sync(this.app, friend.users[i].user)];
                case 6:
                    _a.sent();
                    _a.label = 7;
                case 7:
                    i++;
                    return [3 /*break*/, 5];
                case 8:
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.verifyFriend = function (uid, friendId, isAgree, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, friend, i;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.Model.findById(friendId).exec()];
                case 2:
                    friend = _a.sent();
                    if (!friend) {
                        console.warn("!friend");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (!friend.users.find(function (u) { return u.user.equals(uid); })) {
                        console.warn("!friend.users.find(u => u.user.equals(uid))");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (friend.isVerified) {
                        console.warn("friend.isVerified");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (friend.addBy.equals(uid)) {
                        console.warn("friend.addBy.equals(uid)");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (!isAgree)
                        return [3 /*break*/, 4];
                    friend.isVerified = true;
                    return [4 /*yield*/, friend.save()];
                case 3:
                    friend = _a.sent();
                    return [3 /*break*/, 6];
                case 4: return [4 /*yield*/, friend.remove()];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6:
                    i = 0;
                    _a.label = 7;
                case 7:
                    if (!(i < friend.users.length))
                        return [3 /*break*/, 10];
                    return [4 /*yield*/, Friend.sync(this.app, friend.users[i].user)];
                case 8:
                    _a.sent();
                    _a.label = 9;
                case 9:
                    i++;
                    return [3 /*break*/, 7];
                case 10:
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.removeFriend = function (uid, friendId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, friend, i;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.Model.findById(friendId).exec()];
                case 2:
                    friend = _a.sent();
                    if (!friend) {
                        console.warn("!friend");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (!friend.users.find(function (u) { return u.user.equals(uid); })) {
                        console.warn("!friend.users.find(u => u.user.equals(uid))");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (!friend.isVerified && !friend.addBy.equals(uid)) {
                        console.warn("!friend.isVerified && !friend.addBy.equals(uid)");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, friend.remove()];
                case 3:
                    _a.sent();
                    i = 0;
                    _a.label = 4;
                case 4:
                    if (!(i < friend.users.length))
                        return [3 /*break*/, 7];
                    return [4 /*yield*/, Friend.sync(this.app, friend.users[i].user)];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6:
                    i++;
                    return [3 /*break*/, 4];
                case 7:
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.signIn = function (uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, gameData, s, nowDay, lastDay, item;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!appData");
                        cb(0);
                        return [2 /*return*/];
                    }
                    s = 86400000;
                    nowDay = Math.floor(new Date().valueOf() / s);
                    lastDay = Math.floor(user.signInAt / s);
                    if (nowDay <= lastDay) {
                        console.warn("nowDay <= lastDay");
                        cb(0);
                        return [2 /*return*/];
                    }
                    item = gameData.signInRewards[user.signInDays % gameData.signInRewards.length];
                    user.signInDays++;
                    user.signInAt = new Date().valueOf();
                    user = User.addItem(user, item.id, item.amount);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.sendMessage = function (uid, sendToUid, message, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, sendToUser, friend, msg, maxMsg, statusService;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!message) {
                        console.warn("!message");
                        cb(0);
                        return [2 /*return*/];
                    }
                    message = common.validMessage(message);
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(sendToUid).exec()];
                case 2:
                    sendToUser = _a.sent();
                    if (!sendToUser) {
                        console.warn("!sendToUser");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.find(user._id, sendToUser._id)];
                case 3:
                    friend = _a.sent();
                    if (!friend) {
                        console.warn("!friend");
                        cb(0);
                        return [2 /*return*/];
                    } // 不是朋友
                    msg = {
                        sender: user._id,
                        sendAt: new Date().valueOf(),
                        text: message,
                    };
                    friend.messages.push(msg);
                    maxMsg = 10;
                    if (friend.messages.length > maxMsg) {
                        friend.messages.splice(0, friend.messages.length - maxMsg);
                    }
                    return [4 /*yield*/, friend.save()];
                case 4:
                    friend = _a.sent();
                    statusService = this.app.get('statusService');
                    statusService.pushByUids(friend.users.map(function (uid) { return uid.user.toString(); }), "onSendMessage", {
                        friendId: friend._id,
                        message: msg,
                    }, function (err, fails) {
                        cb(1);
                    });
                    return [2 /*return*/];
            }
        });
    });
};
remote.sendGlobalMessage = function (uid, message, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, gameData, e, channelService;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!message) {
                        console.warn("!message");
                        cb(0);
                        return [2 /*return*/];
                    }
                    message = common.validMessage(message);
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!appData");
                        cb(0);
                        return [2 /*return*/];
                    }
                    e = gameData.events.find(function (e) { return e.id == "sendGlobalMessage"; });
                    if (!e) {
                        console.warn("!e");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.currencys.gold < e.price) {
                        console.warn("user.currencys.gold < e.price");
                        cb(2);
                        return [2 /*return*/];
                    }
                    user.currencys.gold -= e.price;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    channelService = this.app.get('channelService');
                    channelService.broadcast("connector", "onSendGlobalMessage", {
                        user: {
                            name: User.getName(user),
                        },
                        message: message,
                    }, {}, function () {
                        cb(1);
                    });
                    return [2 /*return*/];
            }
        });
    });
};
remote.rename = function (uid, newName, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, gameData, e;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!newName) {
                        console.warn("!name");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.customData.name == newName) {
                        console.warn("user.customData.name == newName");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!gameData");
                        cb(0);
                        return [2 /*return*/];
                    }
                    e = gameData.events.find(function (e) { return e.id == "rename"; });
                    if (!e) {
                        console.warn("!e");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.currencys.gold < e.price) {
                        console.warn("user.currencys.gold < e.price");
                        cb(2);
                        return [2 /*return*/];
                    }
                    user.customData.name = newName;
                    user.currencys.gold -= e.price;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.denaturation = function (uid, newIsMale, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, gameData, e;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.customData.isMale == newIsMale) {
                        console.warn("user.customData.isMale == newIsMale");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!gameData");
                        cb(0);
                        return [2 /*return*/];
                    }
                    e = gameData.events.find(function (e) { return e.id == "denaturation"; });
                    if (!e) {
                        console.warn("!e");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.currencys.gold < e.price) {
                        console.warn("user.currencys.gold < e.price");
                        cb(2);
                        return [2 /*return*/];
                    }
                    user.customData.isMale = newIsMale;
                    user.currencys.gold -= e.price;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.updateIconPath = function (uid, iconPath, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.customData.iconPath == iconPath) {
                        console.warn("user.customData.iconPath == iconPath");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.customData.iconPath = iconPath;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.updateCoverUrl = function (uid, coverUrl, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.coverUrl == coverUrl) {
                        console.warn("user.coverUrl == coverUrl");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.coverUrl = coverUrl;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.initCustomData = function (uid, customData, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user.customData = customData;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    user = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.readFriendMessage = function (uid, friendId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, friend, friendUser;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.Model.findById(friendId).exec()];
                case 2:
                    friend = _a.sent();
                    if (!friend) {
                        console.warn("!friend");
                        cb(0);
                        return [2 /*return*/];
                    }
                    friendUser = friend.users.find(function (u) { return u.user.equals(uid); });
                    if (!friendUser) {
                        console.warn("!friendUser");
                        cb(0);
                        return [2 /*return*/];
                    }
                    friendUser.readAt = Date.now();
                    return [4 /*yield*/, friend.save()];
                case 3:
                    friend = _a.sent();
                    cb(1, friendUser.readAt);
                    return [2 /*return*/];
            }
        });
    });
};
remote.getDailyTaskClearList = function (uid, taskId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var result, user, game;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    result = {
                        clears: [],
                        amounts: [],
                    };
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(result);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({})];
                case 2:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb(result);
                        return [2 /*return*/];
                    }
                    result.clears = game.dailyTasks.filter(function (t) { return User.canClearDailyTask(user, t); }).map(function (t) { return t.id; });
                    result.amounts = game.dailyTasks.map(function (t) { return User.getTaskAmount(user, t); });
                    cb(result);
                    return [2 /*return*/];
            }
        });
    });
};
remote.clearDailyTask = function (uid, taskId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, game, task;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb(0);
                        return [2 /*return*/];
                    }
                    task = game.dailyTasks.find(function (t) { return t.id == taskId; });
                    if (!task) {
                        console.warn("!task");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (!User.canClearDailyTask(user, task)) {
                        console.warn("!User.tryClearDailyTask(user, task)");
                        cb(0);
                        return [2 /*return*/];
                    }
                    user = User.clearDailyTask(user, task);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.getPlayingRoom = function (uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, rooms, room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(-1, false);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.findRooms(user._id)];
                case 2:
                    rooms = _a.sent();
                    if (rooms.length == 0) {
                        console.warn("rooms.length == 0");
                        cb(-1, false);
                        return [2 /*return*/];
                    }
                    room = rooms[rooms.length - 1];
                    player = room.players.find(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (!player) {
                        console.warn("!player");
                        cb(-1, false);
                        return [2 /*return*/];
                    }
                    cb(room.number, player.deadInfo.state == 0);
                    return [2 /*return*/];
            }
        });
    });
};
remote.payment = function (uid, productId, platform, orderId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var game, product, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Game.Model.findOne({})];
                case 1:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb();
                        return [2 /*return*/];
                    }
                    product = game.paymentProducts.find(function (p) { return p.id == productId; });
                    if (!product) {
                        console.warn("!product");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, PaymentRecord.apply(this.app, user, product, platform, orderId)];
                case 3:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.getGiftRecords = function (uid, userToId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var records;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, GiftRecord.Model.find({ userTo: userToId }).exec()];
                case 1:
                    records = _a.sent();
                    cb(records);
                    return [2 /*return*/];
            }
        });
    });
};
remote.follow = function (uid, followUid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, followUser;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    if (user.following.findIndex(function (f) { return f.toString() == followUid; }) >= 0) {
                        console.warn("user.following.findIndex(f => f.toString() == followUid) >= 0");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(followUid).exec()];
                case 2:
                    followUser = _a.sent();
                    if (!followUser) {
                        console.warn("!followUser");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!followUser.isAnchor) {
                        console.warn("!followUser.isAnchor");
                        cb();
                        return [2 /*return*/];
                    }
                    user.following.push(followUser._id);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 3:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  群组
 */
remote.createGroup = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/];
        });
    });
};
/**
 * @see   添加一条狼人杀比赛报名信息
 */ // session  msg cb 
remote.insertOneMatchInfo = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var userLen;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Match.Model.count({ "account": uid, "joinNumber": { "$gt": 0 } })];
                case 1:
                    userLen = _a.sent();
                    /**
                     * @  错误编号：
                     * 	0【您已成功注册！】 success
                     * 1【用户名称不能空！】
                     * 2【身份证不能空！】
                     * 3【手机号码不能空！】
                     * 4【俱乐部名不能空！】
                     * 5【输入的身份证号不合法！】
                     * 6【输入的手机不合法！】
                     * 7【该账号已经报名了比赛！】
                     * 8【用户名称非法！】
                     * 9【输入的用户名称长度不能大于20！】
                     * 1【用户名称不能空！】
                     */
                    if (userLen) {
                        console.warn("该账号已经报名了比赛！");
                        cb({ status: "7", msg: "该账号已经报名了比赛！" });
                        return [2 /*return*/];
                    }
                    //获取索引
                    //   let joinNum =  await  sequence.getNextSequenceValue();
                    //   if(!joinNum){
                    // 		console.warn("请初始化数据库索引！"); cb({ status: "8", msg: "请初始化数据库索引！" }); return; 
                    //   }
                    return [4 /*yield*/, Match.insertItem(this.app, uid, msg.name, msg.clubName, msg.IdNumber, msg.phone)];
                case 2:
                    //获取索引
                    //   let joinNum =  await  sequence.getNextSequenceValue();
                    //   if(!joinNum){
                    // 		console.warn("请初始化数据库索引！"); cb({ status: "8", msg: "请初始化数据库索引！" }); return; 
                    //   }
                    _a.sent();
                    cb({
                        status: "0",
                        joinNum: -1,
                        msg: "您已成功注册！"
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  根据当前user的uid查询----->当前用户的注册信息
 */
remote.findOneMatchInfoForUid = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var match;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Match.Model.findOne({ "account": uid }).exec()];
                case 1:
                    match = _a.sent();
                    if (!match) {
                        console.warn("没有查询到当前用户的注册信息！");
                        cb();
                        return [2 /*return*/];
                    }
                    cb({
                        state: "1",
                        msg: match
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  更新支付信息
 *
 * name     clubName     joinNumber    IdNumber  phone
 */
remote.updatePaymentInfoForMatch = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var match, joinNum;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Match.Model.findOne({ "account": uid }).exec()];
                case 1:
                    match = _a.sent();
                    if (!match) {
                        console.warn("没有查询到当前用户的注册信息！");
                        cb({
                            status: "1", msg: "没有查询到当前用户的注册信息！"
                        });
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, sequence.getNextSequenceValue()];
                case 2:
                    joinNum = _a.sent();
                    console.log(joinNum);
                    if (!joinNum) {
                        console.warn("请初始化数据库索引！");
                        cb({ status: "1", msg: "请初始化数据库索引！" });
                        return [2 /*return*/];
                    }
                    //更新数据
                    return [4 /*yield*/, Match.Model.findOneAndUpdate({ "account": uid }, { $set: { "orderId": msg.orderId, "joinNumber": joinNum } })];
                case 3:
                    //更新数据
                    _a.sent();
                    cb({ status: "0", msg: "success", joinNum: joinNum.toString() });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  用户兑换商品扣除积分
 *
 * name     clubName     joinNumber    IdNumber  phone
 */
remote.exchangeCreditsGoods = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, gameData, exchangeGood, storeInfo;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb({ status: "0" });
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 2:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!appData");
                        cb({ status: "0" });
                        return [2 /*return*/];
                    }
                    exchangeGood = gameData.exchangeGoods.find(function (e) { return e.id == msg.id; });
                    if (!exchangeGood) {
                        console.warn("!exchangeGood");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (user.credits < exchangeGood.amount * msg.count) {
                        console.warn("积分不够不够兑换指定商品！");
                        cb({ status: "0" });
                        return [2 /*return*/];
                    }
                    storeInfo = gameData.partners.find(function (p) { return !!p && p.id == msg.storeId; });
                    if (!storeInfo) {
                        console.warn("!game.partners");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, CreditGoods.insertItem(uid, user.name, msg.count, msg.id, exchangeGood.name, exchangeGood.amount, exchangeGood.amount * msg.count, msg.storeId, storeInfo.store[0].name)];
                case 3:
                    _a.sent();
                    user.credits -= exchangeGood.amount * msg.count;
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 4:
                    // CreditGoods.
                    user = _a.sent();
                    cb({ status: "1" });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  用户新增或者更新地址信息
 */
remote.insertOrUpdateAddrInfo = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!common.isPhoneLegal(msg.phone)) {
                        cb({
                            state: "2",
                            msg: "您输入的手机号码不合法！"
                        });
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb({ state: "0" });
                        return [2 /*return*/];
                    }
                    User.Model.findOneAndUpdate({ _id: uid }, {
                        $set: {
                            addressInfo: {
                                name: msg.name,
                                phone: msg.phone,
                                address: msg.address
                            }
                        }
                    }, {
                        upsert: true
                    }, function (err) {
                        if (err) {
                            cb({ state: "0" });
                            return common.insertDbError(err);
                        }
                    });
                    user.addressInfo = {
                        name: msg.name,
                        phone: msg.phone,
                        address: msg.address
                    };
                    // sync  to  client	
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 2:
                    // sync  to  client	
                    _a.sent();
                    cb({
                        state: "1",
                        msg: "success!"
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see   查询用户所有的礼物类型
 */
remote.findAllExistGoodsInfo = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var gameData, user, goodItems, i, j, address;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Game.Model.findOne({}).exec()];
                case 1:
                    gameData = _a.sent();
                    if (!gameData) {
                        console.warn("!gameData");
                        cb({ state: "0" });
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb({ state: "0" });
                        return [2 /*return*/];
                    }
                    goodItems = gameData.items.filter(function (g) { return !!g && !g.isDailyTask && g.costType == "task"; });
                    //将用户拥有的商品数量  同步到goodItems   里面
                    if (user.inventory.length) {
                        for (i = 0; i < user.inventory.length; i++) {
                            for (j = 0; j < goodItems.length; j++) {
                                if (user.inventory[i].id == goodItems[j].id) {
                                    goodItems[j].userOwn = user.inventory[i].amount;
                                }
                            }
                        }
                    }
                    address = user.addressInfo;
                    cb({
                        state: "1",
                        msg: "success",
                        address: address,
                        userGoldCount: user.currencys.gold,
                        goodItems: goodItems,
                        realItems: gameData.realItems
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  获取地址信息
 */
remote.getAddressInfo = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, address;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb({ state: "0" });
                        return [2 /*return*/];
                    }
                    address = user.addressInfo;
                    if (!address) {
                        console.warn("!addressInof");
                        cb({ state: "0", msg: "没有查询到地址信息" });
                        return [2 /*return*/];
                    }
                    cb({
                        state: "1",
                        msg: address
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  获取所有的好友信息
 */
remote.getFriendsInfo = function (uid, msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, totalRecords, friends, oneWins, oneLoses, i, friend, friendUser, _a, records, i_1;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _b.sent();
                    if (!user) {
                        console.warn("!user");
                        cb({ state: "0" });
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Friend.sync(this.app, uid)];
                case 2:
                    _b.sent();
                    totalRecords = [];
                    return [4 /*yield*/, Friend.Model.find({ users: { $elemMatch: { user: uid } } }).exec()];
                case 3:
                    friends = _b.sent();
                    oneWins = 0;
                    oneLoses = 0;
                    i = 0;
                    _b.label = 4;
                case 4:
                    if (!(i < friends.length))
                        return [3 /*break*/, 7];
                    friend = friends[i];
                    friendUser = friend.users.find(function (u) { return !u.user.equals(uid); });
                    if (!friendUser)
                        return [3 /*break*/, 6];
                    _a = friend;
                    return [4 /*yield*/, User.Model.findById(friendUser.user)];
                case 5:
                    _a.friendUser = (_b.sent());
                    console.warn(friend.friendUser);
                    records = friend.friendUser.roleRecords;
                    if (!records)
                        return [3 /*break*/, 6];
                    for (i_1 = 0; i_1 < records.length; i_1++) {
                        if (records[i_1].wins) {
                            oneWins += records[i_1].wins;
                        }
                        if (records[i_1].loses) {
                            oneLoses += records[i_1].loses;
                        }
                    }
                    totalRecords.push({
                        wins: oneWins,
                        loses: oneLoses
                    });
                    _b.label = 6;
                case 6:
                    i++;
                    return [3 /*break*/, 4];
                case 7:
                    cb({
                        state: "1",
                        totalRecords: totalRecords
                    });
                    return [2 /*return*/];
            }
        });
    });
};
